<%@ page language="java" contentType="text/html; charset=UTF-8" %>

<%@ page import="org.apache.commons.lang3.StringUtils,weaver.conn.RecordSet" %>
<%@ page import="weaver.general.Util"%>
<%@ page import="weaver.hrm.resource.ResourceComInfo"%>
<%@ page import="weaver.integration.logging.Logger" %>
<%@ page import="weaver.integration.logging.LoggerFactory" %>
<%@ page import="weaver.interfaces.outter.CheckIpNetWorkForUpcoming" %>
<%@ page import="javax.crypto.Cipher" %>
<%@ page import="javax.crypto.spec.SecretKeySpec" %>
<%@ page import="java.math.BigInteger" %>
<%@ page import="java.nio.charset.StandardCharsets" %>
<%@ include file="/systeminfo/init_wev8.jsp" %>

<%
    Logger log = LoggerFactory.getLogger();

    RecordSet rs = new RecordSet();

    String workflowId = request.getParameter("workflowid");
    String sysId = request.getParameter("sysid");
	String isMsg = Util.null2String(request.getParameter("_weaverofsmsg"));

    int userId = user.getUID() ;
    String pcurl ;
    if(StringUtils.isNotBlank(workflowId)){
        //新建异构系统
        log.error("workflowid="+workflowId);
        rs.executeQuery("select * from ofs_workflow where workflowid = ?",workflowId);
        rs.next();
        pcurl = rs.getString("pccwurl");
        if ("".equals(Util.null2String(sysId))){
            sysId = rs.getString("SYSID");
        }
    }else{
        //访问异构系统流程
        String todoDataId = request.getParameter("tododataid");
        log.error("todoDataId="+todoDataId);
        String isRemark = request.getParameter("isremark");
        log.error("isRemark="+isRemark);

        if( "0".equals(isRemark) || "8".equals(isRemark)){
            rs.executeQuery("select * from ofs_todo_data where id = ?",todoDataId);
            rs.next();
            pcurl =  Util.null2String(rs.getString("pcurlsrc"));
            if ("".equals(Util.null2String(sysId))){
                sysId = rs.getString("SYSID");
            }
        }else{
            rs.executeQuery("select * from ofs_done_data where id = ?",todoDataId);
            rs.next();
            pcurl =  Util.null2String(rs.getString("pcurlsrc"));
            if ("".equals(Util.null2String(sysId))){
                sysId = rs.getString("SYSID");
            }
        }
    }

    rs.executeQuery("select * from ofs_sysinfo where sysid = ?" , sysId);
    if(rs.next()){

        //自动内外网登录
        String clientIp = Util.getIpAddr(request);
        boolean notInOuter = this.notInOuter(rs.getString("syscode") , clientIp);

        String prefixURL ;
        if (notInOuter){
            prefixURL = Util.null2String(rs.getString("pcouterfixurl"));
        }else{
            prefixURL = Util.null2String(rs.getString("pcprefixurl"));
        }

        String tokenUrl = this.getToken(pcurl , userId+"") ;
		if ("".equals(tokenUrl)){
			out.println("get Token is null ");
			return ;
		}
//		if (tokenUrl.contains(":")){
//			out.println("get Token is err : " + tokenUrl);
//			return ;
//		}
		
        String toURL = tokenUrl;
        log.error("pc端访问异构系统地址："+toURL);
%>
<script type="text/javascript">

    location.replace('<%=toURL%>');

</script>
<%

    }else{
        log.error("根据标识："+sysId+"未查询到数据");
        return;
    }


%>

<%!
    Logger log = LoggerFactory.getLogger();

    //外网地址返回 true ,内网 false
    private boolean notInOuter(String sysCode , String clientIp){

        //0代表不开启，则所有通过内网访问
        //1代表开启，并且有设置网段
        //2代表开启，但是没有设置网段
        RecordSet rs = new RecordSet();
        rs.executeQuery("SELECT * FROM autologin_status WHERE syscode= ? " , sysCode) ;
        if (rs.next()){
            String status = Util.null2String(rs.getString("status"),"0");
            if ("0".equals(status)){
                return false ;
            }else if ("2".equals(status)){
                return true ;
            }
        }
        //检测IP
        CheckIpNetWorkForUpcoming checkIpNetWorkForUpcoming = new CheckIpNetWorkForUpcoming();
        return checkIpNetWorkForUpcoming.checkIpSeg(clientIp);//不在网段策略中 返回true
    }

    private String getToken(String prefixURL ,String userid){
        String result = "";
        String key = "36C7311E32067875"; // 加密密钥
        String ssoKey = "ICf7IVwCdK2MODaC";//授权信息
        try {
            ResourceComInfo resourceComInfo = new ResourceComInfo();
            String workcode = Util.null2String(resourceComInfo.getWorkcode(userid));
            String encryptedHex = encryptEmployeeId(workcode, key);
            result = prefixURL+"?ssotoken=" + ssoKey + "&ticket=" +encryptedHex;
        } catch (Exception e) {
            e.printStackTrace();
        }
       return result;
    }


    private String encryptEmployeeId(String employeeId, String key) throws Exception {

        // 创建AES密钥
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");

        // 创建Cipher对象
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 加密数据
        byte[] encryptedBytes = cipher.doFinal(employeeId.getBytes(StandardCharsets.UTF_8));

        // 将加密后的字节数组转换为HEX编码
        String hexEncoded = bytesToHex(encryptedBytes);

        return hexEncoded;
    }

    private String bytesToHex(byte[] bytes) {
        BigInteger bi = new BigInteger(1, bytes);
        String hex = bi.toString(16);
        int paddingLength = (bytes.length * 2) - hex.length();
        if (paddingLength > 0) {
            return String.format("%0" + paddingLength + "d", 0) + hex;
        } else {
            return hex;
        }
    }

%>